﻿using BulkUploadGovernanceFiles.Models;
using System;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using BulkUploadGovernanceFiles.MoveInsightToS3Buckets;
using BulkUploadGovernanceFiles.Repositories;
using BulkUploadGovernanceFiles.SyncroniseInsights;

namespace BulkUploadGovernanceFiles
{
    public partial class Form1 : Form
    {
        private CancellationTokenSource _tokenSource;
        private readonly UploadProcessor _uploadProcessor;

        public Form1()
        {
            InitializeComponent();
            _uploadProcessor = new UploadProcessor();
            try
            {
                _uploadProcessor = new UploadProcessor();

            }
            catch (Exception exception)
            {

                btnUpdateBusinessAndFinancialProfile.Enabled = false;
                btnCancel.Enabled = false;
                //btnRemoveAll.Enabled = false;
                btnSyncroniseInsights.Enabled = false;
                cekDeleteAfterProcessing.Enabled = false;
                MessageBox.Show(exception.Message);
            }
            InitializeInfoLabels();
            
        }

        private void InitializeInfoLabels()
        {
            lblCorporateDataDatabase.Text = ConfigManager.ClientDw.ConnectionString;
            lblMetadataDatabase.Text = ConfigManager.GovernanceInputFile.ConnectionString;
            lblFilesFolder.Text = ConfigManagement.FilePath;
            lblGovernanceDWdatabase.Text = ConfigManager.GovernanceDw.ConnectionString;

            progressBar1.Value = 0;
        }

        private async void btnSelectFolder_Click(object sender, EventArgs e)
        {
            _tokenSource = new CancellationTokenSource();
            SetProgressBar(_uploadProcessor.FileCollection.Count());
            btnUpdateBusinessAndFinancialProfile.Enabled = false;
            await _uploadProcessor.Process(cekDeleteAfterProcessing.Checked, _tokenSource.Token, Progress(), GovernancePdfType.BusinessAndFinancialProfile);
            btnUpdateBusinessAndFinancialProfile.Enabled = true;
            lblStatus.Text = _uploadProcessor.StatusMessage; 
        }

        private Progress<int> Progress()
        {
            var progress = new Progress<int>(percent =>
            {
                progressBar1.Increment(1);
                lblStatus.Text = "File number: " + percent;
            });
            return progress;
        }

        private void SetProgressBar(int numberOfFiles)
        {
            lblStatus.Text = "";
            progressBar1.Value = 0;
            progressBar1.Maximum = numberOfFiles;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (_tokenSource != null)
                _tokenSource.Cancel();
        }

        private void btnRemoveAll_Click(object sender, EventArgs e)
        {
            //DialogResult dr = MessageBox.Show("All the information regarding pdf will be removed from the mongo database", "Remove all from mongo db", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

            //if (dr == DialogResult.Yes)
            //{
            //    _uploadProcessor.DeleteAllFiles();
            //}
            //InitializeInfoLabels();
        }

        #region BackgroundWorker

        //private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        //{
        //    progressBar1.Increment(e.ProgressPercentage);
        //}

        //private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        //{
        //    var test = e.Result;
        //    //this.Text = test.ToString() ;
        //    //lblStatus.Text = test.ToString();
        //    int i = 1;
        //}

        //private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        //{
        //    //var bgWorker = (BackgroundWorker)sender;
        //    //(e.Argument as BulkUploadManagement).Start(bgWorker);
        //}

        //private void StartWithBW()
        //{
        //    BulkUploadManagement bulkUploadManagement = new BulkUploadManagement();
        //    SetProgressBar(bulkUploadManagement.NumberOfFiles);

        //    BackgroundWorker bgWorker = new BackgroundWorker
        //    {
        //        WorkerReportsProgress = true,
        //        WorkerSupportsCancellation = true
        //    };
        //    bgWorker.DoWork += bgWorker_DoWork;

        //    bgWorker.RunWorkerAsync(bulkUploadManagement);

        //    bgWorker.RunWorkerCompleted += bgWorker_RunWorkerCompleted;
        //    bgWorker.ProgressChanged += bgWorker_ProgressChanged;
        //}

        #endregion

        private void btnSyncroniseInsights_Click(object sender, EventArgs e)
        {
            btnSyncroniseInsights.Enabled = false;
            new ProcessCompanyProfile().Process();
            lblSyncStatus.Text = "Done";
        }

        private int _numberOfInsightsFile;
        private async void btnMove_Click(object sender, EventArgs e)
        {
            //_tokenSource = new CancellationTokenSource();
            //var insightRepository = new InsightRepository();
            //var mongoGridFsRepository = new MongoGridFSRepository(ConfigManager.ClientPlatform.DataBaseName,ConfigManager.ClientPlatform.ConnectionString);
            //var s3BucketUpload = new S3BucketFileUpload();
            //var processInsights = new ProcessInsights(insightRepository,mongoGridFsRepository,  s3BucketUpload);
            //SetS3ProgressBar(processInsights.NumberOfFiles);
            //await processInsights.Process(_tokenSource.Token, S3Progress());
        }

        private Progress<int> S3Progress()
        {
            var progress = new Progress<int>(percent =>
            {
                s3ProgressBar.Increment(1);
                lblS3Move.Text = "File number: " + percent + "from " + _numberOfInsightsFile;
            });
            return progress;
        }
        private void SetS3ProgressBar(int numberOfFiles)
        {
            _numberOfInsightsFile = numberOfFiles;
            lblStatus.Text = "";
            progressBar1.Value = 0;
            progressBar1.Maximum = numberOfFiles;
        }

        private async void btnUpdateGovernanceDataProfile_Click(object sender, EventArgs e)
        {
            _tokenSource = new CancellationTokenSource();
            SetProgressBar(_uploadProcessor.FileCollection.Count());
            btnUpdateBusinessAndFinancialProfile.Enabled = false;
            await _uploadProcessor.Process(cekDeleteAfterProcessing.Checked, _tokenSource.Token, Progress(), GovernancePdfType.GovernanceDataProfile);
            btnUpdateBusinessAndFinancialProfile.Enabled = true;
            lblStatus.Text = _uploadProcessor.StatusMessage;
        }

        private void btnClearBusinessProfile_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("All the information regarding pdf will be removed from the mongo database and S3", "Remove all from mongo db", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

            if (dr == DialogResult.Yes)
            {
                _uploadProcessor.DeleteAllFiles(GovernancePdfType.BusinessAndFinancialProfile);
            }
            InitializeInfoLabels();
        }

        private void btnClearDataProfiles_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("All the information regarding pdf will be removed from the mongo database and S3", "Remove all from mongo db", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

            if (dr == DialogResult.Yes)
            {
                _uploadProcessor.DeleteAllFiles(GovernancePdfType.GovernanceDataProfile);
            }
            InitializeInfoLabels();
        }
    }
}
